#!/bin/bash
source comm.cfg

# 标记是否所有端口都启动成功
all_ports_up=1

color_text() {
    local color=$1
    local text=$2
    echo -e "\e[${color}m${text}\e[0m"
}

error() {
    color_text "31" "$1"
}

info() {
    color_text "32" "$1"
}

function installprom() {
    version=2.45.3
    filename=prometheus-${version}.linux-amd64
    mkdir -p /opt/prometheus
    wget https://github.com/prometheus/prometheus/releases/download/v${version}/${filename}.tar.gz
    tar xf ${filename}.tar.gz
    cp -far ${filename}/*  /opt/prometheus/

# service 
cat <<EOF >/etc/systemd/system/prometheus.service
[Unit]
Description="prometheus"
Documentation=https://prometheus.io/
After=network.target

[Service]
Type=simple

ExecStart=/opt/prometheus/prometheus --config.file=/opt/prometheus/prometheus.yml --storage.tsdb.path=/opt/prometheus/data --web.enable-lifecycle --web.enable-remote-write-receiver

Restart=on-failure
SuccessExitStatus=0
LimitNOFILE=65536
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=prometheus

[Install]
WantedBy=multi-user.target
EOF
    systemctl enable prometheus
    systemctl restart prometheus
}

function installn9e() {
    if [ ! -d "$N9E_PATH" ];then
    mkdir $N9E_PATH -p
    fi
    # 下载并安装夜莺
    wget https://download.flashcat.cloud/n9e-${N9EVERSION}-linux-amd64.tar.gz -P $N9E_PATH
    if [ $? -ne 0 ];then
        echo '下载错误，请检查下载链接是否正常'
        echo "https://download.flashcat.cloud/n9e-${N9EVERSION}-linux-amd64.tar.gz"
        exit 1
    fi
    tar xvf $N9E_PATH/n9e-${N9EVERSION}-linux-amd64.tar.gz -C $N9E_PATH
    cat <<EOF >/etc/systemd/system/n9e.service
[Unit]
Description="n9e.service"
After=network.target

[Service]
Type=simple
ExecStart=${N9E_PATH}/n9e
WorkingDirectory=${N9E_PATH}
Restart=on-failure
SuccessExitStatus=0
LimitNOFILE=65536
[Install]
WantedBy=multi-user.target
EOF
    systemctl daemon-reload
    systemctl enable n9e.service
    # 配置n9e配置文件
    sed -i -e '/KeepHours/s/^#\ //' -e '/RotateSize/s/^#\ //' -e '/RotateNum/s/^#\ //' $N9E_PATH/etc/config.toml
    sed -i /Level/s/DEBUG/INFO/ $N9E_PATH/etc/config.toml
    sed -i /Output/s/stdout/file/ $N9E_PATH/etc/config.toml
    sed -i /KeepHours/s/4/48/ $N9E_PATH/etc/config.toml
    sed -i /^DSN/s/1234/${MYSQL_ROOT_PASSWORD}/ $N9E_PATH/etc/config.toml
    sed -i "s/^#\?\s*Password\s*=\s*".*"/Password = \"$REDIS_PASSWORD\"/" $N9E_PATH/etc/config.toml
    mysql -uroot -p${MYSQL_ROOT_PASSWORD} < $N9E_PATH/n9e.sql
    if [ $? -eq 0 ];then
        info "导入数据库成功"
    else
        error "导入数据库失败"
    fi
    systemctl start n9e.service
    
    # 检查启动是否成功
    ss -tlnp|grep 17000
    if [ $? -ne 0 ];then
        info "正在等待n9e 启动..."
        sleep 20
        ss -tlnp|grep 17000
        if [ $? -eq 0 ];then
            info "n9e安装成功"
            info "请浏览器访问：节点IP:17000，默认用户是 root，密码是 root.2020"
        else
            error "n9e启动失败，请检查日志 journalctl -fu n9e"
        fi
    fi
}

# 安装数据库
function installdb() {
    # 更新包列表
    sudo apt-get update
    # 安装MySQL Server
    sudo apt-get install -y mysql-server=8.0.*
    info "Setting the root password..."
    sudo mysql -e "ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY ${MYSQL_ROOT_PASSWORD};"
    sudo mysql -e "FLUSH PRIVILEGES;"
    info "MySQL has been installed"

    # 安装必需的依赖
    sudo apt-get install -y gnupg2 ca-certificates curl
    # 添加Redis的GPG密钥
    curl -sL https://packages.redis.io/gpg | sudo gpg --dearmor -o /usr/share/keyrings/redis-archive-keyring.gpg
    # 添加Redis的APT源
    echo "deb [signed-by=/usr/share/keyrings/redis-archive-keyring.gpg] https://packages.redis.io/deb $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/redis.list
    # 更新包列表以包含Redis
    sudo apt-get update
    # 安装Redis
    sudo apt-get install redis -y
    sed -i "s/bind 127.0.0.1/bind 0.0.0.0/g" /etc/redis/redis.conf
    sed -i "561i maxmemory-policy allkeys-lru" /etc/redis/redis.conf
    sed -i "792i requirepass $REDIS_PASSWORD" /etc/redis/redis.conf
    sudo systemctl restart redis-server

    # 安装postgres
    sudo apt install postgresql-14 -y

    # 检查是否启动成功
    port_list="3306 6379 5432"
    for i in ${port_list} ; do
        if [[ -z $(ss -nlpt | grep -w ":$i") ]] ; then
            info "正在等待${i}端口启动..."
            sleep 20
            if [[ -z $(ss -nlpt | grep -w ":$i") ]] ; then
                error "$i 端口启动失败"
                all_ports_up=0
            fi
        fi
    done
    if [[ $all_ports_up -eq 1 ]]; then
        info "依赖数据库启动成功"
    else
        error "有端口启动失败，请检查对应错误信息"
        # 还原 port 标志状态
        all_ports_up=1
    fi
}

function installmaas() {
    # 创建 MaaS 数据库用户
    sudo -u postgres psql -c "CREATE USER \"maascli\" WITH PASSWORD 'a3f876fb3286e8bf304c01064e080fae'"
    sudo -u postgres createdb -O "maascli" "maasclidb"
    # 可以修改成其他版本
    sudo snap install --channel=${MAASVERSION} maas
    # 初始化 MaaS 数据库
    sudo maas init region+rack --database-uri "postgres://maascli:a3f876fb3286e8bf304c01064e080fae@localhost/maasclidb"
    if [ $? -ne 0 ];then
        error "初始化maas服务失败"
    else
        info "初始化maas成功"
    fi
}

function installjms() {
    jmsdatadir=`grep VOLUME_DIR config-example.txt | awk -F '=' '{print $2}'`
    if [ ! -d $jmsdatadir ];then
        mkdir -p $jmsdatadir
    fi
    # 配置jumpserver
    info "正在下载${JMSVERSION}版本jumpserver..."
    wget https://github.com/jumpserver/installer/releases/download/${JMSVERSION}/jumpserver-installer-${JMSVERSION}.tar.gz
    info "正在解压${JMSVERSION}版本jumpserver..."
    tar xf ./jumpserver-installer-${JMSVERSION}.tar.gz -C ${jmsdatadir}
    if [ $? -ne 0 ];then
        error "解压出错，请当前目录是否正确下载${JMSVERSION}版本的压缩包"
        exit
    fi
    # 创建jms用户名密码，只在一台上创建用户名密码就行
    sudo mysql -uroot -p${MYSQL_ROOT_PASSWORD} -e "create database jumpserver default charset 'utf8';"
    sudo mysql -uroot -p${MYSQL_ROOT_PASSWORD} -e "create user 'jumpserver'@'%' identified by 'jumpserver';"
    sudo mysql -uroot -p${MYSQL_ROOT_PASSWORD} -e "grant all on jumpserver.* to 'jumpserver'@'%';"
    sudo mysql -uroot -p${MYSQL_ROOT_PASSWORD} -e "flush privileges;"

    sed -i "s/REDIS_PASSWORD=.*/REDIS_PASSWORD=$REDIS_PASSWORD/" config-example.txt
    cp ./config-example.txt ${jmsdatadir}/jumpserver-installer-${JMSVERSION}
    # 安装并启动jms
    # 安装
    ${jmsdatadir}/jumpserver-installer-${JMSVERSION}/jmsctl.sh install
    # 启动
    ${jmsdatadir}/jumpserver-installer-${JMSVERSION}/jmsctl.sh start
    # 检查是否启动成功
    port_list="81 2222 3389"
    for i in ${port_list} ; do
        if [[ ! `ss -nlpt | grep -w :${i}` ]] ; then
            info "正在等待${i}端口启动"
            sleep 10
            if [[ ! `ss -nlpt | grep -w :${i}` ]] ; then
                error "$i 异常端口，jumpserver启动失败"
            fi
        else
            info "$i 端口正常"
        fi
    done
}

function installhaproxy() {
    sudo apt-get install haproxy -y
    sed -i "s/MAASDOMIND/$MAASDOMIND/" haproxy.cfg
    sed -i "s/N9EDOMIND/$N9EDOMIND/" haproxy.cfg
    sed -i "s/JMSDOMIND/$JMSDOMIND/" haproxy.cfg
    cp haproxy.cfg /etc/haproxy/haproxy.cfg
    systemctl restart haproxy
    if [ $? -ne 0 ];then
        error "启动 haproxy 失败，请检查 haproxy 日志 /var/log/haproxy.log"
    else
        info "安装 haproxy 成功，管理地址：http://主机IP:8080"
    fi
    info "所有服务访问地址如下：
    jumpserver: http://$JMSDOMIND admin admin
    夜莺： http://$N9EDOMIND root，密码是 root.2020
    maas: http://$MAASDOMIND
    maas服务请在节点执行sudo maas createadmin创建admin用户，然后在浏览器登录"
}

main() {
    echo "请输入要安装的服务编号:"
    echo "1. 安装mysql、redis、pg数据库"
    echo "2. 安装jumpserver"
    echo "3. 安装maas"
    echo "4. 安装夜莺"
    echo "5. 安装haproxy"
    echo "6. 安装全部服务"
    echo "0. Exit"
    read -p "Enter your choice (0-6): " choice
    case $choice in
        1) installdb ;;
        2) installjms ;;
        3) installmaas ;;
        4) installprom; installn9e ;;
        5) installhaproxy ;;
        6) echo "Executing all functions..."; installdb; installjms; installmaas; installn9e ;;
        0) echo "Exiting..."; exit 0 ;;
        *) echo "Invalid choice. Please try again." ; main ;;
    esac
}

main